package org.ee.rabbitmq.service;

import org.ee.rabbitmq.model.RabbitTopic;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 *
 * @Author zlj
 * @Date 2025/11/10 22:57
 */
@Component
public class RabbitService {

    private final AmqpAdmin amqpAdmin;
    private final RabbitTemplate rabbitTemplate;

    public RabbitService(AmqpAdmin amqpAdmin, RabbitTemplate rabbitTemplate) {
        this.amqpAdmin = amqpAdmin;
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 动态声明主题（队列、交换机、绑定关系）
     */
    public void declareTopic(RabbitTopic topic) {
        Queue queue = new Queue(topic.getQueue(), true);
        DirectExchange exchange = new DirectExchange(topic.getExchange());
        Binding binding = BindingBuilder.bind(queue)
                .to(exchange)
                .with(topic.getRoutingKey());
        amqpAdmin.declareExchange(exchange);
        amqpAdmin.declareQueue(queue);
        amqpAdmin.declareBinding(binding);
    }

    /**
     * 发送消息
     */
    public void send(RabbitTopic topic, Object message) {
        rabbitTemplate.convertAndSend(topic.getExchange(), topic.getRoutingKey(), message);
    }
}